package org.xiaojinlong.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AtomicityTest implements Runnable {
    // 如果一个域完全由synchronized方法或语句块来防护，那就不必将其设置为是volatile的
    private int i = 0;
    public synchronized int getValue() { return i; }
    private synchronized void evenIncrement() { i++; Thread.yield(); i++; }
    public void run() {
        while (true)
            evenIncrement();
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        AtomicityTest at = new AtomicityTest();
        exec.execute(at);
        while (true) {
            int val = at.getValue();
            if (val % 2 != 0) {
                System.out.println(val);
                System.exit(0);
            }
        }
    }
}
